package MetroLab.Path;

import MetroLab.Utils.ObjectFactory;
import MetroLab.Utils.PathRes;
import com.sun.j3d.utils.geometry.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.*;
import javax.media.j3d.*;
import javax.media.j3d.ImageComponent2D.Updater;
import javax.vecmath.*;

/**
 * 一个各面都显示速度仪表的搞笑的无聊的盒子~
 * @author plus
 */
public class SpeedCube extends Group {

    private TransformGroup TGRoot;
    private Group cubeRoot;
    private BufferedImage SpeedDashBack=null, SpeedDashBackImg=null;
    private ImageComponent2D ic2D=null;
    private static final Polygon SpeedDashPointer=new Polygon(new int[]{4,4,1,0,-1,-4,-4},
            new int[]{0,15,20,35,20,15,0},7);
    
    public SpeedCube() {
        super();
        initCube();
        this.addChild(TGRoot);
    }

    private void initCube() {
        Transform3D t3d = new Transform3D();
        t3d.set(new Vector3d(50, 50, -50));
        TGRoot = new TransformGroup(t3d);
        
        Appearance app = new Appearance();
        ObjectFactory.SetMaterialToAppearance(app);
        app.setTexture(initTexture());
        TextureAttributes texAtt = new TextureAttributes();
        texAtt.setTextureMode(TextureAttributes.MODULATE);
        app.setTextureAttributes(texAtt);
        
        cubeRoot = (new Box(30, 30, 30,Box.GENERATE_TEXTURE_COORDS, app));
        TGRoot.addChild(cubeRoot);
    }
    
    private Texture initTexture(){
        try{
            if (SpeedDashBack==null)
                SpeedDashBackImg=ImageIO.read(new File(PathRes.getPath("Image.SpeedDashBack")));
                SpeedDashBack=ImageIO.read(new File(PathRes.getPath("Image.SpeedDashBack")));
        }catch(Exception e){
            e.printStackTrace();
        }
        
        drawImage(80);
        
        ic2D=new ImageComponent2D(ImageComponent.FORMAT_RGBA,SpeedDashBack,true, false);
        ic2D.setCapability(ic2D.ALLOW_IMAGE_WRITE);
        
        Texture2D textOut=new Texture2D(Texture.BASE_LEVEL,Texture.RGBA, 256,256);
        textOut.setImage(0, ic2D);
        return textOut;
    }
    
    public void updateSpeed(double speed){
        drawImage(speed);
        ic2D.updateData(new Updater(){
            public void updateData(ImageComponent2D in, int x, int y, int w, int h) {}
        }, 0, 0, 256, 256);
    }
    private void drawImage(double speed){
        Graphics2D g2= (Graphics2D)SpeedDashBack.getGraphics();
        //g2.clearRect(0, 0, 256, 256);
        g2.drawImage(SpeedDashBackImg,null,null);
        g2.translate(126, 128);
        g2.rotate((double)Math.abs(speed)/200d*(Math.PI*2-2.12)+1.06d);
        g2.translate(0, 22);
        g2.setPaint(Color.yellow);
        g2.fill(SpeedDashPointer);
    }
}
